<template>
  <div class="app-container">
    <div class="pagecontent alarmanage_content">
      <div class="alarmanage_left">
        <div class="alarmanage_map">
          <div v-if="isUpload == 'nopic'" class="alarmange_layer">
            <div class="alarmange_tipcontent">
              <div class="alarmange_tip">
                <i
                  class="iconfont iconshanchujinzhi"
                  style="font-size: 100px"
                />
                <span>{{ $t("common.cnode") }}</span>
              </div>
            </div>
          </div>
          <div v-if="imgSrc" class="alarmange_layer">
            <div class="alarmange_tipcontent">
              <el-upload
                class="change-uploader"
                :show-file-list="false"
                :before-upload="beforeupload"
                :expand-on-click-node="false"
                drag
                action=""
              >
                <div class="alarmange_tip">
                  <i class="iconfont iconadd" style="font-size: 100px" />
                  <span>{{ $t("common.cpicture") }}</span>
                </div>
              </el-upload>
            </div>
          </div>
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeupload"
            :expand-on-click-node="false"
            drag
            action=""
          >
            <img
              v-if="imgSrc"
              :src="imgSrc"
              style="height: 100%"
              class="avatar"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </div>
      </div>

      <div class="alarmanage_right">
        <div class="alarmanage_maptree">
          <div class="alarmanage_right_button">
            <el-button type="primary" size="mini" @click="appendmp()">{{
              $t("operating.add")
            }}</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="onSubmit('formValue')"
            >{{ $t("map.save") }}</el-button>
          </div>
          <div class="alarmanage_right_maptree">
            <el-tree
              ref="tree"
              class="spanBtn"
              :data="mapTreeArr"
              current-node-key
              highlight-current
              :props="defaultProps"
              node-key="id"
              :default-expand-all="true"
              :expand-on-click-node="false"
              @node-click="nodeClick"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span>
                  <el-button type="text" @click.stop="editTree(data)">
                    <i class="el-icon-edit" style="font-size: 14px" />
                  </el-button>
                  <el-button type="text" @click.stop="removeTree(node, data)">
                    <i class="el-icon-delete" />
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </div>

        <div class="alarmanage_map_info">
          <el-input
            v-model="imgSrc"
            style="width: 600px"
            :disabled="true"
            type="hidden"
          />
          <el-form
            ref="formValue"
            :label-position="labelPosition"
            label-width="150px"
            :rules="rules"
            :model="formValue"
          >
            <el-form-item :label="$t('map.mapName')" prop="mapName">
              <el-input v-model="formValue.mapName" :disabled="true" />
            </el-form-item>

            <el-form-item
              :label="$t('common.fuser')"
              prop="lcid"
              :rules="filter_rules({ required: $t('map.lcidRule') })"
            >
              <el-select
                v-model="formValue.lcid"
                filterable
                :placeholder="$t('operating.pleaseChosen')+$t('common.fuser')"
                style="width: 150px"
              >
                <el-option
                  v-for="item in fuserList"
                  :key="item.fuserLcid"
                  :label="item.fuserName"
                  :value="item.fuserLcid"
                />
              </el-select>
            </el-form-item>

            <el-form-item

              :label="$t('map.layerId')"
              prop="layerId"
              :rules="filter_rules({ required: $t('map.layerIdRule') })"
            >
              <el-input
                v-model="formValue.layerId"
                :placeholder="$t('operating.pleaseWrite')+$t('map.layerId')"
              />
            </el-form-item>

            <el-form-item

              :label="$t('map.mapPixelX')"
              prop="mapPixelX"
              :rules="
                filter_rules({
                  type: 'isZero',
                  required: $t('map.mapPixelXRule'),
                })
              "
            >
              <el-input
                v-model="formValue.mapPixelX"
                :placeholder="$t('operating.pleaseWrite')+$t('map.mapPixelX')"
              />
            </el-form-item>

            <el-form-item
              :label="$t('map.mapPixelY')"
              prop="mapPixelY"
              :rules="
                filter_rules({
                  type: 'isZero',
                  required: $t('map.mapPixelYRule'),
                })
              "
            >
              <el-input
                v-model="formValue.mapPixelY"
                :placeholder="$t('operating.pleaseWrite')+$t('map.mapPixelY')"
              />
            </el-form-item>

            <el-form-item
              :label="$t('map.mapActualX')"
              prop="mapActualX"
              :rules="
                filter_rules({
                  type: 'isZero',
                  required: $t('map.mapActualXRule'),
                })
              "
            >
              <el-input
                v-model="formValue.mapActualX"
                :placeholder="$t('operating.pleaseWrite')+$t('map.mapActualX')"
              />
            </el-form-item>

            <el-form-item
              :label="$t('map.mapActualY')"
              prop="mapActualY"
              :rules="
                filter_rules({
                  type: 'isZero',
                  required: $t('map.mapActualYRule'),
                })
              "
            >
              <el-input
                v-model="formValue.mapActualY"
                :placeholder="$t('operating.pleaseWrite')+$t('map.mapActualY')"
              />
            </el-form-item>

            <el-form-item
              :label="$t('map.mapOriginX')"
              prop="mapOriginX"
              :rules="filter_rules({ required: $t('map.mapOriginXRule') })"
            >
              <el-input
                v-model="formValue.mapOriginX"
                type="number"
                :placeholder="$t('operating.pleaseWrite')+$t('map.mapOriginX')"
              />
            </el-form-item>

            <el-form-item
              :label="$t('map.mapOriginY')"
              prop="mapOriginY"
              :rules="filter_rules({ required: $t('map.mapOriginXRule') })"
            >
              <el-input
                v-model="formValue.mapOriginY"
                type="number"
                :placeholder="$t('operating.pleaseWrite')+$t('map.mapOriginY')"
              />
            </el-form-item>

            <el-form-item :label="$t('operating.remark')" prop="remark">
              <el-input
                v-model="formValue.remark"
                :placeholder="$t('operating.pleaseWrite')+$t('operating.remark')"
              />
            </el-form-item>

            <!--是否启用-->
            <el-form-item class="isEnable" :label="$t('map.isEnable')">
              <el-switch
                v-model="switchVal"
                inactive-value="0"
                active-value="1"
                active-color="#ffc000"
                inactive-color="#dcdfe6"
                @change="isSwitch"
              />
            </el-form-item>

            <!-- <el-form-item class="submitBtn">
                <el-button type="primary" @click="onSubmit('formValue')">{{
                  $t("map.save")
                }}</el-button>
              </el-form-item> -->
          </el-form>
        </div>
      </div>

      <!--编辑弹出框 $t('operating.handle')
      this.editEnable = false
      -->
      <el-dialog
        :title="editEnable ? $t('operating.add') : $t('operating.handle')"
        :close-on-click-modal="false"
        :visible.sync="editVisible"
        :before-close="handleClose"
        width="400px"
      >
        <el-form
          ref="deptForm"
          :model="deptForm"
          label-width="120px"
          :rules="rulesTree"
        >
          <!--父级名称-->
          <el-form-item :label="$t('map.ParentNode')" prop="parentId">
            <treeselect
              v-model="deptForm.parentId"
              :placeholder="$t('operating.pleaseChosen')"
              :show-count="true"
              :max-height="600"
              :options="mapTreeList"
              :default-expand-level="1"
              style="width: 215px; margin-right: 10px"
              @input="nodeClickTree"
            />
          </el-form-item>

          <!--子级名称-->
          <el-form-item :label="$t('map.childenNode')" prop="childenNode">
            <!-- :rules="filter_rules({ required: '请输入地图名称' })" -->
            <el-input
              v-model="deptForm.childenNode"
              style="max-width: 215px"
              :placeholder="$t('operating.pleaseChosen')"
            />
          </el-form-item>
        </el-form>
        <!--操作-->
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            class="edit_confirm"
            @click="saveEdit('deptForm')"
          >{{ $t("operating.determine") }}</el-button>
          <el-button @click="hideDepForm()">{{
            $t("operating.cancel")
          }}</el-button>
        </span>
      </el-dialog>

      <el-dialog
        :title="$t('operating.prompt')"
        :close-on-click-modal="false"
        :visible.sync="defaultMapVisible"
        width="400px"
      >
        <div class="del-dialog-cnt">{{ $t("map.defaultMap") }}</div>

        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            class="delete_confirm"
            @click="defaultMap"
          >{{ $t("operating.determine") }}</el-button>
          <el-button @click="defaultMapVisible = false">{{
            $t("operating.cancel")
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { baseUrl } from '@/utils/global.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import {
  areaTree,
  deleteMap,
  fuserList,
  getMap,
  mapDefault,
  saveAndEditMap,
  addMapNode
} from '@/api/cy.js'
export default {
  components: { Treeselect },
  data() {
    return {
      delWS: null,
      value: '',
      mapTreeArr: [],
      mapTreeList: [],
      mapId: '', // 选中的地图id
      imgSrc: '', // 地图路径
      labelPosition: 'right', // 表单label文字对齐方式
      formValue: {
        mapurl: '', // 地图地址
        mapName: '', // 地图名称
        lcid: '', // fuserid
        layerId: null, // 层号
        mapPixelX: null, // 像素宽度
        mapPixelY: null, // 像素高度
        mapActualY: null, // 实际长度
        mapActualX: null, // 实际宽度
        mapOriginX: null,
        mapOriginY: null,
        remark: '' // 地图备注
      },
      switchVal: '0', // 是否启用
      editVisible: false, // 增加地图树弹窗是否显示
      delVisible: false, // 删除地图树弹窗是否显示
      defaultMapVisible: false,
      editEnable: true, // 点击的编辑or添加
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      file: new FormData(), // 地图文件
      // 表单验证规则
      rules: {},
      rulesTree: {
        parentId: [
          {
            required: true,
            message: this.$i18n.t('common.ctoprule'),
            trigger: 'blur'
          }
        ],
        childenNode: [
          {
            required: true,
            message: this.$i18n.t('common.csecondrule'),
            trigger: 'blur'
          }
        ]
      },

      deptForm: { parentId: '', ParentNode: '', childenNode: '' },
      nodeName: '',
      parentId: 0,
      fuserList: '',
      idxMap: '',
      idxNode: '',
      // isActive: false,//输入框是否禁用

      isUpload: 'nopic',
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  mounted() {
    this.initMapTree()
    this.getFuserList()
  },
  methods: {
    handleClose(done) {
      this.resetForm('deptForm')
      done()
    },
    hideDepForm() {
      this.resetForm('deptForm')
      this.editVisible = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    nodeClickTree(val) {
      console.log('树节点被点击', val, this.deptForm.parentId, this.deptForm)
    },

    // 获取Fuser数据
    getFuserList() {
      fuserList().then((res) => {
        this.fuserList = res.rows
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单提交的事件
          this.file.append('idx', this.mapId)
          this.file.append('type', 'layer')
          this.file.append('nodeName', this.nodeName)
          this.file.append('parentId', this.parentId)
          this.file.append('mapName', this.formValue.mapName)
          this.file.append('lcid', this.formValue.lcid)
          this.file.append('layerId', this.formValue.layerId)
          this.file.append('mapPixelX', this.formValue.mapPixelX)
          this.file.append('mapPixelY', this.formValue.mapPixelY)
          this.file.append('mapActualY', this.formValue.mapActualY)
          this.file.append('mapActualX', this.formValue.mapActualX)
          this.file.append('mapOriginX', this.formValue.mapOriginX)
          this.file.append('mapOriginY', this.formValue.mapOriginY)
          this.file.append('remark', this.formValue.remark)
          this.file.append('isDefault', this.switchVal)
          mapDefault().then((result) => {
            if (result.code === 200) {
              if ('data' in result) {
                if (parseInt(result.data.idx) !== parseInt(this.mapId)) {
                  if (this.switchVal == '1') {
                    this.defaultMapVisible = true
                  } else {
                    this.saveMap(this.file)
                  }
                } else {
                  this.saveMap(this.file)
                }
              } else {
                this.saveMap(this.file)
              }
            }
          })
        }
      })
    },
    saveMap() {
      saveAndEditMap(this.file, {
        'Content-Type':
          'multipart/form-data;boundary = ' + new Date().getTime()
      })
        .then((map) => {
          if (map.code === 200) {
            this.msgSuccess(map.msg)
          }
          this.file = new FormData()
        })
        .catch((e) => {
          this.file = new FormData()
          this.msgError(e.msg)
        })
    },

    // 是否有默认地图
    isSwitch(val) {
      this.switchVal = val
    },

    /** ***************************************************************************/
    // 树节点被点击时调用
    nodeClick(draggingNode, dropNode, ev) {
      // 可将地图的ID设置为树结构的ID，通过点击节点，来切换地图
      // that.v_MyMessage("选择的树分支ID：" + draggingNode.id, "success");
      if (this.$refs['formValue']) {
        this.$refs['formValue'].resetFields()
      }
      this.mapId = draggingNode.id
      this.formValue.mapName = draggingNode.label
      this.nodeName = draggingNode.label
      if (draggingNode.parentId) {
        this.parentId = draggingNode.parentId
      }
      // if (draggingNode.id) {
      //   this.deptForm['parentId'] = draggingNode.id
      // }
      // this.isUpload = 'uploadpic' // 隐藏图层
      getMap(this.mapId).then((result) => {
        // let RES = this.responseUse(result.data);

        this.isUpload = 'uploadpic' // 隐藏图层
        const RES = result.data

        if (!RES.mapPath) {
          this.imgSrc = ''
          this.$message.info(this.$i18n.t('common.maptip'))
        } else {
          this.imgSrc = baseUrl + '/file' + RES.mapPath
        }

        // this.formValue={
        //   mapurl: RES.mapPath,
        //   mapName: RES.nodeName, //地图名称
        //   lcid: RES.lcid, //fuserid
        //   layerId: RES.layerId, //层号
        //   mapPixelX: RES.mapPixelX, //像素宽度
        //   mapPixelY: RES.mapPixelY, //像素高度
        //   mapActualY: RES.mapActualY, //实际长度
        //   mapActualX: RES.mapActualX, //实际宽度
        //   mapOriginX: RES.mapOriginX,
        //   mapOriginY: RES.mapOriginY,
        //   remark:''
        // };

        if (
          RES.mapPath != '' &&
          RES.mapPath != undefined &&
          RES.mapPath != null
        ) {
          this.formValue['mapurl'] = RES.mapPath
        }
        if (
          RES.nodeName != '' &&
          RES.nodeName != undefined &&
          RES.nodeName != null
        ) {
          this.formValue['mapName'] = RES.nodeName
        }
        if (RES.lcid != '' && RES.lcid != undefined && RES.lcid != null) {
          this.formValue['lcid'] = RES.lcid
        }
        if (
          RES.layerId || RES.layerId == 0
        ) {
          this.formValue['layerId'] = RES.layerId
        }

        if (
          RES.mapPixelX != '' &&
          RES.mapPixelX != undefined &&
          RES.mapPixelX != null
        ) {
          this.formValue['mapPixelX'] = RES.mapPixelX
        }
        if (
          RES.mapPixelY != '' &&
          RES.mapPixelY != undefined &&
          RES.mapPixelY != null
        ) {
          this.formValue['mapPixelY'] = RES.mapPixelY
        }
        if (
          RES.mapActualY != '' &&
          RES.mapActualY != undefined &&
          RES.mapActualY != null
        ) {
          this.formValue['mapActualY'] = RES.mapActualY
        }
        if (
          RES.mapActualX != '' &&
          RES.mapActualX != undefined &&
          RES.mapActualX != null
        ) {
          this.formValue['mapActualX'] = RES.mapActualX
        }
        if (
          RES.mapOriginX != '' &&
          RES.mapOriginX != undefined &&
          RES.mapOriginX != null
        ) {
          this.formValue['mapOriginX'] = RES.mapOriginX
        }
        if (
          RES.mapOriginY != '' &&
          RES.mapOriginY != undefined &&
          RES.mapOriginY != null
        ) {
          this.formValue['mapOriginY'] = RES.mapOriginY
        }

        if (RES.remark != '' && RES.remark != undefined && RES.remark != null) {
          this.formValue['remark'] = RES.remark
        }
        if (
          RES.isDefault != '' &&
          RES.isDefault != undefined &&
          RES.isDefault != null
        ) {
          this.switchVal = RES.isDefault + ''
        } else {
          this.switchVal = '0'
        }
      })
    },
    // 阻止upload的自己上传，进行再操作
    beforeupload(file) {
      const fileNameArr = file.name.split('.')
      const typeName = fileNameArr[fileNameArr.length - 1].toLocaleLowerCase()
      if (typeName != 'jpg' && typeName != 'png' && typeName != 'jpeg') {
        this.$message(this.$i18n.t('common.cpictureTip'))
        return false
      }

      // 创建临时的路径来展示图片
      const windowURL = window.URL || window.webkitURL
      this.imgSrc = windowURL.createObjectURL(file)

      this.file.append('file', file)
      return false
    },

    defaultMap() {
      saveAndEditMap(this.file, {
        'Content-Type':
          'multipart/form-data;boundary = ' + new Date().getTime()
      })
        .then((res) => {
          if (res.code == 500) {
            this.file = new FormData()
            this.v_MyMessage(res.msg, 'warning')
            this.defaultMapVisible = false
          } else if (res.code == 200) {
            this.file = new FormData()
            this.defaultMapVisible = false
            this.v_MyMessage(this.$t('Notice.mapAddedSuccessfully'), 'success')
          }
        })
        .catch((e) => {
          this.file = new FormData()
        })
    },
    // 添加地图
    appendmp() {
      this.editEnable = true
      this.editVisible = true
      // console.log(this.deptForm)

      // this.deptForm = { parentId: '0' }
      if (
        this.mapId === '' ||
        this.mapId === null ||
        this.mapId === undefined
      ) {
        this.mapId = 0
        this.nodeName = ''
        this.deptForm = { ParentNode: '', parentId: '0', childenNode: '' }
      } else {
        this.deptForm = {
          ParentNode: this.nodeName,
          parentId: '0',
          childenNode: ''
        }
      }
    },

    // 编辑
    editTree(data) {
      this.editVisible = true
      this.editEnable = false
      this.nodeName = data.label
      this.parentId = data.parentId
      this.idxNode = data.id
      this.deptForm['parentId'] = data.parentId
      if (data.label) {
        this.deptForm['childenNode'] = data.label
      } else {
        this.deptForm['childenNode'] = ''
      }
      if (data.parentName) {
        this.deptForm['ParentNode'] = data.parentName
      } else {
        this.deptForm['ParentNode'] = ''
      }
    },
    // 确定添加
    saveEdit(formName) {
      const that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let param
          if (this.editEnable) {
            param = {
              parentId: this.deptForm.parentId,
              // parentId: that.mapId,
              nodeName: that.deptForm.childenNode
            }
          } else {
            param = {
              // parentId: this.parentId,
              parentId: this.deptForm.parentId,
              nodeName: this.deptForm.childenNode,
              idx: this.idxNode
            }
          }
          addMapNode(param).then((res) => {
            if (res.code == 200) {
              this.editVisible = false
              this.msgSuccess(res.msg)
              setTimeout(() => {
                this.initMapTree()
              }, 1500)
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    // 删除地图
    removeTree(node, data) {
      // this.delVisible = true;
      this.$confirm(
        this.$i18n.t('common.cdelTipItem') + data.label,
        this.$i18n.t('common.cwarn'),
        {
          confirmButtonText: this.$i18n.t('common.cok'),
          cancelButtonText: this.$i18n.t('common.ccancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.idxMap = [{ idx: data.id }]
          return deleteMap(this.idxMap)
        })
        .then(() => {
          this.msgSuccess(this.$i18n.t('common.cdelSuccess'))
          this.delVisible = false
          this.formValue.mapurl = ''
          this.formValue.mapName = ''
          this.formValue.lcid = ''
          this.formValue.layerId = null
          this.formValue.mapPixelX = null
          this.formValue.mapPixelY = null
          this.formValue.mapActualX = null
          this.formValue.mapOriginX = null
          this.formValue.mapOriginY = null
          this.formValue.remark = ''
          this.resetForm('formValue')
          setTimeout(() => {
            this.initMapTree()
          }, 1500)
        })
    },

    initMapTree() {
      areaTree()
        .then((res) => {
          if (res.code == 200) {
            const tempData = [
              {
                disabled: false,
                id: '0',
                isDefault: 0,
                // label: '首级',
                label: this.$i18n.t('common.ctop'),
                parentId: '0'
              }
            ]
            this.mapTreeList = [...tempData, ...res.data]
            this.mapTreeArr = res.data
          }
        })
        .catch((error) => {
          console.log(error)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.alarmanage_map:hover .alarmange_layer {
  display: block !important;
}

.alarmanage_content {
  display: flex;
  height: 100%;
  .alarmanage_left {
    margin: 10px 0px;
    flex: 1;
    // height: 915px;
    width: calc(100% - 360px);
    .alarmanage_map {
      height: 100%;
      position: relative;
      .alarmange_layer {
        display: none;
        position: absolute;
        background: #a0a0a08a;
        width: 100%;
        height: 100%;
        z-index: 10;
        .alarmange_tipcontent {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .alarmange_tip {
          font-size: 30px;
          color: #fff;
          display: flex;
          justify-content: center;
          flex-direction: column;
          align-items: center;
        }
      }

      .avatar-uploader {
        position: relative;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      // .el-upload-dragger {
      //   display: flex;
      //   justify-content: center;
      //   align-items: center;
      //   font-size: 30px;
      // }
    }
  }
  .alarmanage_right {
    width: 350px;
    margin: 10px;
    height: 97%;
    box-shadow: 0 0 8px -2px grey;
    // border: 1px solid #8f8f8f;
    border-radius: 8px;
    .alarmanage_right_maptree {
      height: 150px;
      overflow: auto;
      margin: 10px auto;
    }

    .alarmanage_maptree,
    .alarmanage_map_info {
      // border: 1px solid #3333;
      padding: 20px 10px;
      // margin-bottom: 15px;
    }
    .alarmanage_maptree {
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 15px;
    }
    // .el-form-item {
    //   margin-bottom: 28px;
    // }
  }
}
.alarmanage_map_info {
  padding: 0px 10px !important;
  height: calc(100% - 267px);
  overflow-x: hidden;
  width: 100%;
}

span.custom-tree-node {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-right: 20px;
}
</style>

<style scoped>
.change-uploader /deep/.el-upload-dragger {
  background: none;
  padding: 24px;
  border: 3px dashed #fff;
}
.alarmanage_map >>> i.el-icon-plus.avatar-uploader-icon {
  font-size: 60px;
  color: #888888;
}
.alarmanage_map >>> .el-upload.el-upload--text,
.alarmanage_map >>> .el-upload-dragger {
  width: 100%;
  height: 100%;
}
.alarmanage_map >>> .el-upload-dragger {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
}
</style>
